
#include <BPainter>
#include <BEvent>
#include "member_BWidget.h"
#include "member_BPixmap.h"
#include "member_BImage.h"
#include "member_BTexture.h"

using namespace BWE;

member_BPixmap::member_BPixmap(BPixmap* pixmap)
{
	boss = pixmap;
	size.set(1920, 1080);

	dirty = true;
	fbo = 0;
	rbo_depth = 0;
	rbo_stencil = 0;

	drag = 0;
	hoverWidget = 0;
	focusWidget = 0;
}
member_BPixmap::~member_BPixmap()
{

}

bool member_BPixmap::check() const
{
	GLenum state = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	switch (state)
	{
	case GL_FRAMEBUFFER_COMPLETE:
		return true;
	case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
		puts("FBO Initialization Failed : incomplete attachment");
		return false;
	case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
		puts("FBO Initialization Failed : missing attachment");
		return false;
	case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
		puts("FBO Initialization Failed : draw buffer is invalid");
		return false;
	case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
		puts("FBO Initialization Failed : read buffer is invalid");
		return false;
	case GL_FRAMEBUFFER_UNSUPPORTED:
		puts("FBO Initialization Failed : this is not supported");
		return false;
	}

	return 0 != glIsFramebuffer(fbo);
}

void member_BPixmap::update(const BEvent& event)
{
	for (int i = widgets.size() - 1; i >= 0; i--)
	{
		BWidget* rootWidget = widgets[i];
		updateWidget(rootWidget, event);
	}
	if (refresh)
		boss->dirty();
}
void member_BPixmap::fresh()
{
	BEvent event(Event_Fresh);
	for (int i = widgets.size() - 1; i >= 0; i--)
	{
		BWidget* rootWidget = widgets[i];
		freshWidget(rootWidget, event);
	}
}
void member_BPixmap::frame()
{
	if (fbo == 0 || rbo_depth == 0)
		fbo_resized = true;

	if (fbo_resized)
	{
		GLint backup_frame_buffer;
		glGetIntegerv(GL_FRAMEBUFFER_BINDING, &backup_frame_buffer);

		int width = size.width();
		int height = size.height();

		glGenFramebuffers(1, &fbo);
		if (!fbo)
			return;

		GLuint tbo = texture_member(boss)->tbo;
		glBindFramebuffer(GL_FRAMEBUFFER, fbo);
		{
			glGenRenderbuffers(1, &rbo_depth);
			glBindRenderbuffer(GL_RENDERBUFFER, rbo_depth);
			glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
			glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo_depth);

			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
			glBindTexture(GL_TEXTURE_2D, tbo);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0);
			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, tbo, 0);
		}
		fbo_resized = false;
		glBindFramebuffer(GL_FRAMEBUFFER, backup_frame_buffer);
	}

	if (fbo)
	{
		state.save();

		for (int i =0; i < widgets.size(); i++)
		{
			BWidget* rootWidget = widgets[i];
			frameWidget(rootWidget);
		}

		glBindFramebuffer(GL_FRAMEBUFFER, fbo);
		glDrawBuffer(GL_COLOR_ATTACHMENT1);
		glReadBuffer(GL_COLOR_ATTACHMENT1);

		glClearColor(color.r() / 255.0f, color.g() / 255.0f, color.b() / 255.0f, color.a() / 255.0f);
		glClear(GL_COLOR_BUFFER_BIT);
		glDisable(GL_LIGHTING);
		glDisable(GL_DEPTH_TEST);
		glDisable(GL_CULL_FACE);

		glViewport(0, 0, size.width(), size.height());

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0, size.width(), size.height(), 0, -1, 1);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		BRect clip = size;

		glEnable(GL_TEXTURE_2D);
		for (int i = 0; i < widgets.size(); i++)
		{
			BWidget* rootWidget = widgets[i];
			drawWidget(rootWidget, clip, rootWidget->pos(), size.height());
		}
		for (int i = 0; i < popupWidgets.size(); i++)
		{
			BWidget* widget = popupWidgets[i];
			drawPopupWidget(widget, clip, widget->globalPos(), size.height());
		}
		glBindTexture(GL_TEXTURE_2D, 0);
		glDisable(GL_TEXTURE_2D);
		drawCursor();
		//paintDrag();
		drawTips();
		refresh = false;
		boss->emit(Signal_Frame);
		state.open();

		//BPainter painter(boss);
		//glDisable(GL_DEPTH_TEST);
		//painter.setPointSize(3);
		//painter.setPointSmooth(true);
		//painter.setColor(255, 0, 0);
		//painter.drawPoint(mouse_pos);
		//painter.setLineWidth(2);
		//for (int i = popupWidgets.size() - 1; i >= 0; i--)
		//{
		//	BWidget* popupWidget = popupWidgets[i];
		//	painter.drawRect(popupWidget->globalRect());
		//}
	}

}
void member_BPixmap::updateWidget(BWidget* widget, const BEvent& event)
{
	if (widget && widget->enabled())
	{
		widget_member(widget)->procEvent(event);
		if (widget_member(widget)->refresh)
			refresh = true;
		for (int i = 0; i < widget->childCount(); i++)
		{
			BWidget* child = widget->child(i);
			updateWidget(child, event);
		}
	}
}
void member_BPixmap::freshWidget(BWidget* widget, const BEvent& event)
{
	if (widget == 0)
		return;
	if (widget_member(widget)->refresh)
	{
		widget_member(widget)->refresh = false;
		widget_member(widget)->procEvent(event);
		widget_member(widget)->dirty = true;
		refresh = true;
	}
	for (int i = 0; i < widget->childCount(); i++)
	{
		BWidget* child = widget->child(i);
		freshWidget(child, event);
	}
}

bool member_BPixmap::hover(BWidget* widget)
{
	if (hoverWidget != widget)
	{
		hoverWidget = widget;
		if (widget)
			widget->fresh();
	}
	return true;
}
bool member_BPixmap::focus(BWidget* widget)
{
	if (focusWidget != widget)
	{
		if (focusWidget)
		{
			widget_member(focusWidget)->focused = false;
			BEvent focusEvent(Event_Focus);
			focusEvent.setValue(false);
			widget_member(focusWidget)->procEvent(focusEvent);
			focusWidget = 0;
		}
		if (widget && widget->enabled())
		{
			widget_member(widget)->focused = true;
			BEvent focusEvent(Event_Focus);
			focusEvent.setValue(true);
			widget_member(widget)->procEvent(focusEvent);
			focusWidget = widget;

			if (popupWidgets.contain(focusWidget) && popupWidgets.last() != focusWidget)
			{
				popupWidgets.remove(focusWidget);
				popupWidgets.append(focusWidget);
			}
			focusWidget->fresh();
		}
		return true;
	}
	return false;
}
bool member_BPixmap::popup(BWidget* widget, bool flag)
{
	if (flag)
	{
		if (!popupWidgets.contain(widget))
		{
			popupWidgets.append(widget);
		}
		widget->setFocused(true);
	}
	else
	{
		popupWidgets.remove(widget);
		refresh = true;
		return true;
	}
	return false;
}

BWidget* member_BPixmap::widgetUnderPoint(const BPoint& point)
{
	for (int i = popupWidgets.size() - 1; i >= 0; i--)
	{
		BWidget* popupWidget = popupWidgets[i];
		if (!popupWidget->visible())
			continue;
		BWidget* widget = findPopupWidget(popupWidget, point, size);
		if (widget)
			return widget;
		if (popupWidget->modal())
			return 0;
	}
	for (int i = widgets.size() - 1; i >= 0; i--)
	{
		BWidget* rootWidget = widgets[i];
		if (!rootWidget->visible())
			continue;
		BWidget* widget = findWidget(rootWidget, point, size);
		if (widget)
			return widget;
	}
	return 0;
}
BWidget* member_BPixmap::findWidget(BWidget* widget, const BPoint& point, const BRect& clip)
{
	BRect rect = widget->rect();
	BRect clipRect = rect & clip;
	if (!clipRect.contain(point))
		return 0;
	currentRect = clipRect;
	BPoint localPoint = point - rect.pos();
	for (int i = widget_member(widget)->children.size() - 1; i >= 0; i--)
	{
		BWidget* child = widget_member(widget)->children[i];
		if (!child->visible())
			continue;
		if (child->floating())
		{
			BWidget* ret = findWidget(child, localPoint, widget->size());
			if (ret)
				return ret;
			continue;
		}
		const BRect& centerRect = widget->centerRect();
		const BRect& leftRect = widget->rect(Part_Left);
		const BRect& topRect = widget->rect(Part_Top);
		const BRect& rightRect = widget->rect(Part_Right);
		const BRect& bottomRect = widget->rect(Part_Bottom);
		BRect childRect = child->rect();
		if (centerRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, centerRect);
			if (ret)
				return ret;
		}
		if (topRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, topRect);
			if (ret)
				return ret;
		}
		if (leftRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, leftRect);
			if (ret)
				return ret;
		}
		if (rightRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, rightRect);
			if (ret)
				return ret;
		}
		if (bottomRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, bottomRect);
			if (ret)
				return ret;
		}
	}
	return widget;
}
BWidget* member_BPixmap::findPopupWidget(BWidget* widget, const BPoint& point, const BRect& clip)
{
	if (!widget->enabled())
		return 0;

	BRect rect = widget->rect();

	BRect viewRect = widget->absoluteRect() & clip;
	if (!viewRect.contain(point))
		return 0;

	//BPoint localPoint = point - rect.pos();
	BWidgetHolderArray& children = widget_member(widget)->children;
	for (int i = children.size() - 1; i >= 0; i--)
	{
		BWidget* child = widget->child(i);
		if (!child->visible())
			continue;

		if (widget_member(child)->floating)
		{
			BWidget* ret = findPopupWidget(child, point, viewRect);
			if (ret)
				return ret;
		}
		else
		{
			BRect clientViewRect = widget->centerRect();
			clientViewRect += viewRect.pos();
			BWidget* ret = findPopupWidget(child, point, clientViewRect);
			if (ret)
				return ret;
		}
	}

	return widget;
}

void member_BPixmap::frameWidget(BWidget* widget)
{
	if (!widget_member(widget)->visible)
		return;
	BWidgetHolderArray& children = widget_member(widget)->children;
	for (int i = 0; i < children.size(); i++)
	{
		BWidget* child = children[i];
		frameWidget(child);
	}
	if (widget_member(widget)->dirty)
	{
		widget_member(widget)->frame();
	}
}
void member_BPixmap::drawWidget(BWidget* widget, const BRect& clip, const BPoint& offset, int frameHeight)
{
	if (!widget_member(widget)->visible || popupWidgets.contain(widget))
		return;

	BSize size = widget->size();
	BRect ab_rect(offset, size);
	BRect view = ab_rect & clip;
	if (view.empty())
		return;

	glViewport(view.x(), frameHeight - view.bottom(), view.width(), view.height());

	BRect area(view.pos() - ab_rect.pos(), view.size());
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(area.left(), area.right(), area.bottom(), area.top(), -1, 1);

	if (widget_member(widget)->tbo)
	{
		int width = widget_member(widget)->size.width();
		int height = widget_member(widget)->size.height();
		glColor4ub(255, 255, 255, widget_member(widget)->transparency);
		glBindTexture(GL_TEXTURE_2D, widget_member(widget)->tbo);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0f, 1.0f);		glVertex2i(0, 0);
		glTexCoord2f(0.0f, 0.0f);		glVertex2i(0, height);
		glTexCoord2f(1.0f, 0.0f);		glVertex2i(width, height);
		glTexCoord2f(1.0f, 1.0f);		glVertex2i(width, 0);
		glEnd();
	}
	if (!widget_member(widget)->layered)
	{
		BWidgetHolderArray& children = widget_member(widget)->children;
		for (int i = 0; i < children.size(); i++)
		{
			BWidget* child = children[i];
			drawWidget(child, view, offset + child->pos(), frameHeight);
		}
	}
}
void member_BPixmap::drawPopupWidget(BWidget* widget, const BRect& clip, const BPoint& offset, int frameHeight)
{
	if (!widget_member(widget)->visible)
		return;
	BSize size = widget->size();
	BRect ab_rect(offset, size);
	BRect view = ab_rect & clip;
	if (view.empty())
		return;
	glViewport(view.x(), frameHeight - view.bottom(), view.width(), view.height());

	BRect area(view.pos() - ab_rect.pos(), view.size());
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(area.left(), area.right(), area.bottom(), area.top(), -1, 1);

	if (widget_member(widget)->tbo)
	{
		int width = widget_member(widget)->size.width();
		int height = widget_member(widget)->size.height();
		glColor4ub(255, 255, 255, widget_member(widget)->transparency);
		glBindTexture(GL_TEXTURE_2D, widget_member(widget)->tbo);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0f, 1.0f);		glVertex2i(0, 0);
		glTexCoord2f(0.0f, 0.0f);		glVertex2i(0, height);
		glTexCoord2f(1.0f, 0.0f);		glVertex2i(width, height);
		glTexCoord2f(1.0f, 1.0f);		glVertex2i(width, 0);
		glEnd();
	}
	if (!widget_member(widget)->layered)
	{
		BWidgetHolderArray& children = widget_member(widget)->children;
		for (int i = 0; i < children.size(); i++)
		{
			BWidget* child = children[i];
			drawWidget(child, view, offset + child->pos(), frameHeight);
		}
	}
}
void member_BPixmap::drawCursor()
{
	if (!hoverWidget)
		return;
	BPoint point = cursorPos;

	BCursor* cursor = hoverWidget->cursor();
	if (cursor && cursor->type() == Cursor_None)
	{
		BPainter painter(boss);

		BPoint origin = cursor->point();
		BSize size = cursor->size();
		int x = point.x() - origin.x();
		int y = point.y() - origin.y();
		int w = size.width();
		int h = size.height();

		BImage* image = cursor->image();
		if (image)
		{
			painter.setColor(255, 255, 255);
			painter.drawPoint(point);
			painter.drawImage(x, y, w, h, image);
		}
	}
}
void member_BPixmap::drawDrag()
{
	if (!drag)
		return;
	BPoint point = cursorPos;

	BPainter painter(boss);

	BPoint origin;
	BSize size(100, 100);
	int x = point.x() - origin.x();
	int y = point.y() - origin.y();
	int w = size.width();
	int h = size.height();

	BImage* image = drag->image();
	if (image)
	{
		painter.setColor(255, 255, 255);
		painter.drawPoint(point);
		painter.drawImage(x, y, w, h, image);
	}
}
void member_BPixmap::drawTips()
{
	if (!hoverWidget)
		return;

	const BFont* font = hoverWidget->font();
	if (!font)
		return;

	const BString& tooltip = hoverWidget->tips();
	if (tooltip.empty())
		return;

	BSize tipsSize = font->textSize(tooltip);
	BRect tipsRect(tipsPoint, tipsSize);
	BRect rect(boss->size());

	tipsRect.move(23, 23);
	int xoffset = 0;
	int yoffset = 0;
	if (tipsRect.left() < rect.left())
		xoffset += rect.left() - tipsRect.left();
	if (tipsRect.top() < rect.top())
		yoffset += rect.top() - tipsRect.top();
	if (tipsRect.right() > rect.right())
		xoffset += rect.right() - tipsRect.right();
	if (tipsRect.bottom() > rect.bottom())
		yoffset += rect.bottom() - tipsRect.bottom();
	tipsRect.move(xoffset, yoffset);

	BPainter painter(boss);

	if (painter.setColor(Color_Background))
		painter.fillRect(tipsRect);
	if (painter.setColor(Color_Border))
		painter.drawRect(tipsRect);
	if (painter.setColor(Color_Text))
		painter.drawText(tipsRect, tooltip);
	//painter.setPointSize(5);
	//painter.drawPoint(tipsPoint);
}

void member_BPixmap::procMousePress(BMouseEvent& mouseEvent)
{
	mouse_pressed = true;
	mouse_pressed_time = mouseEvent.time();
	mouse_pressed_pos = mouseEvent.globalPos();

	BWidget* widget = widgetUnderPoint(mouse_pressed_pos);
	this->focus(widget);
	if (focusWidget)
	{
		mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->globalPos());
		widget_member(focusWidget)->procEvent(mouseEvent);
	}
}
void member_BPixmap::procMouseRelease(BMouseEvent& mouseEvent)
{
	mouse_pressed = false;

	if (focusWidget)
	{
		mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->globalPos());
		widget_member(focusWidget)->procEvent(mouseEvent);
	}
	if (focusWidget)
	{
		int distance = (mouseEvent.absolutePos() - mouse_pressed_pos).length();
		BReal time = mouseEvent.time();
		BReal interval = time - mouse_pressed_time;
		if (distance < 5 && interval < 1)
		{
			mouseEvent.setType(Event_MouseClick);
			mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->absolutePos());
			widget_member(focusWidget)->procEvent(mouseEvent);
			if (mouse_click_time > 0.000001)
			{
				int distance = (mouseEvent.absolutePos() - mouse_click_pos).length();
				BReal interval = mouseEvent.time() - mouse_click_time;
				if (distance < 4 && interval < 1)
				{
					mouseEvent.setType(Event_DoubleClick);
					mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->globalPos());
					widget_member(focusWidget)->procEvent(mouseEvent);
					mouse_click_time = 0.0;
					mouse_click_pos = BPoint();
					return;
				}
			}
			else
			{
				mouse_click_time = mouseEvent.time();
				mouse_click_pos = mouseEvent.absolutePos();
			}
		}
		else
		{
			mouse_click_time = 0.0;
			mouse_click_pos = BPoint();
		}
	}
}
void member_BPixmap::procMouseMove(BMouseEvent& mouseEvent)
{
	if (focusWidget && mouse_pressed)//block switch hovering widget
	{
		mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->globalPos());
		widget_member(focusWidget)->procEvent(mouseEvent);
		return;
	}

	BPoint absolutePos = mouseEvent.absolutePos();
	BWidget* widget = widgetUnderPoint(absolutePos);
	if (hoverWidget != widget)
	{
		mouse_click_time = 0;
		if (hoverWidget)
		{
			BMouseEvent leaveEvent = mouseEvent;
			leaveEvent.setPos(mouseEvent.absolutePos() - hoverWidget->globalPos());
			leaveEvent.setType(Event_MouseLeave);
			widget_member(hoverWidget)->procEvent(leaveEvent);
		}
		if (widget && widget->enabled())
		{
			BMouseEvent enterEvent = mouseEvent;
			enterEvent.setPos(mouseEvent.absolutePos() - widget->globalPos());
			enterEvent.setType(Event_MouseEnter);
			widget_member(widget)->procEvent(enterEvent);
		}
		hover(widget);
		tipsPoint = absolutePos;
	}
	if (hoverWidget && hoverWidget->enabled())
	{
		mouseEvent.setPos(mouseEvent.absolutePos() - hoverWidget->globalPos());
		widget_member(hoverWidget)->procEvent(mouseEvent);
	}
}
void member_BPixmap::procMouseWheel(BMouseEvent& mouseEvent)
{
	if (focusWidget && focusWidget->enabled())
	{
		widget_member(focusWidget)->procEvent(mouseEvent);
	}
}
void member_BPixmap::procDragMove(BDragEvent& dragEvent)
{
	drag = dragEvent.drag();
	BPoint absolutePos = dragEvent.absolutePos();
	BWidget* widget = widgetUnderPoint(absolutePos);
	if (hoverWidget != widget)
	{
		widget->fresh();
		mouse_click_time = 0;
		if (hoverWidget)
		{
			dragEvent.setCursor(0);
			dragEvent.setType(Event_DragLeave);
			dragEvent.setPos(dragEvent.absolutePos() - hoverWidget->absolutePos());
			widget_member(hoverWidget)->procEvent(dragEvent);
		}
		if (widget && widget->enabled())
		{
			dragEvent.setCursor(0);
			dragEvent.setType(Event_DragEnter);
			dragEvent.setPos(dragEvent.absolutePos() - widget->absolutePos());
			widget_member(widget)->procEvent(dragEvent);
		}
		hover(widget);
	}
	if (hoverWidget && hoverWidget->enabled())
	{
		dragEvent.setType(Event_DragMove);
		dragEvent.setPos(dragEvent.absolutePos() - hoverWidget->absolutePos());
		widget_member(hoverWidget)->procEvent(dragEvent);
	}
}
void member_BPixmap::procDragDrop(BDragEvent& dragEvent)
{
	widget_member(hoverWidget)->procEvent(dragEvent);
	drag = 0;
}

void member_BPixmap::slotImageDirty()
{

}
void member_BPixmap::slotWidgetFramed()
{

}

